package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"lark/consts"
	"lark/proto"
	"lark/util"
	"net"
	"strings"
	"time"
)

var etcdDevcdAddr = "192.168.69.6:22379"
var serviceName = "lark-bench-service"
var cgipass = "tcp://127.0.0.1:14567"

type serviceRegistInfo struct {
	Ip          string `json:"ip"`
	Port        int    `json:"port"`
	ServiceName string `json:"service"`
	WorkNum     int    `json:"worker_num"`
	CgiPass     string `json:"cgi_pass"`
}

func main() {
	ip, err := util.LocalIPByHostsFile()
	util.PanicErr(err)

	echoServer(
		serviceRegistInfo{
			Ip:          ip,
			Port:        12345,
			ServiceName: serviceName,
			WorkNum:     10,
			CgiPass:     cgipass,
		},
		map[string][]string{
			"devcd": []string{etcdDevcdAddr},
		})

}

func keepalive(registInfo serviceRegistInfo, etcdAddr map[string][]string) {
	for {
		conn, err := net.DialTimeout("tcp", "127.0.0.1:12312", time.Second)
		util.PanicErr(err)

		b1, _ := json.Marshal([]serviceRegistInfo{registInfo})
		b2, _ := json.Marshal(etcdAddr)

		proto.NewTLVParser(conn).Send(time.Second, consts.Ps2lsmTagRegistReq, b1, b2)

		conn.Close()
		time.Sleep(time.Second * 3)
	}
}

func echoServer(registInfo serviceRegistInfo, etcdAddr map[string][]string) {
	x := strings.Split(registInfo.CgiPass, "://")
	network := x[0]
	addr := x[1]

	l, err := net.Listen(network, addr)

	util.PanicErr(err)

	go keepalive(registInfo, etcdAddr)

	for {
		conn, err := l.Accept()
		util.PanicErr(err)

		go handleEcho(conn)
	}
}

func handleEcho(conn net.Conn) {
	p := proto.NewlarkProtoV2(conn, time.Minute, time.Second)
	defer p.Close()

	for {
		tag, payload, err := p.Read()
		if err != nil {
			fmt.Println(err)
			return
		}

		if tag != consts.Lsp2psTagTaskReq {
			util.PanicErr(errors.New("tag wrong"))
			return
		}

		err = p.Write(consts.Lsp2psTagTaskRespOK, proto.SplitPayload(payload)[0], nil)
		if err != nil {
			util.PanicErr(err)
			return
		}
	}
}
